<template>
  <div class="app-container">
    <el-form @submit.native.prevent :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="关键字" prop="keyword">
        <el-input
            v-model="queryParams.keyword"
            placeholder="请输入流程标题"
            clearable
            style="width: 300px"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <div style="min-height: 500px; padding: 10px;"  v-loading="loading">
      <el-collapse v-if="rootCategories.length>0" style="min-height: 300px" v-model="activeNames" >
        <el-collapse-item v-for="item in rootCategories" :title="item.name" :name="item.code">
          <div class="model-list-wrapper">
            <el-row>
              <el-col :span="4" v-for="itm in item.modelList">
                <el-card class="model-item-card" shadow="hover" style="margin: 5px;">
                  <div class="model-item" @click="() => {handleLaunch(itm)}">
                    <div class="model-icon">
                      <el-avatar :src="itm.modelIcon"/>
                    </div>
                    <div class="model-name">
                      <el-link type="primary" :underline="false">
                        {{ itm.name }}
                      </el-link>
                    </div>
                  </div>
                  <div class="tool-bar">
                    <el-icon @click="handleBpmnPreview(itm)" ><Picture /></el-icon>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </div>
        </el-collapse-item>
      </el-collapse>
      <el-empty v-else />
    </div>


    <!-- 发起流程对话框 -->
    <el-dialog class="launch-wrapper" :title="title" v-model="processFormVisible" fullscreen append-to-body @close="handleLaunchCancel">
      <div style="position: relative; height: 100%;" v-loading="submitLoading">
        <process-wrapper
            :model-key="currModel.modelKey"
            ref="processWrapperRef"
        />
        <div class="right-btn">
          <el-button type="primary" @click="submitForm">提 交</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 预览流程对话框 -->
    <el-dialog width="1000px"
               :title="bpmnViewerTitle"
               v-model="bpmnViewerVisible"
               append-to-body
               class="bpmn-viewer-body">
      <div style="height: 500px;">
        <BpmnViewer :model-key="previewModelKey" ref="bpmnViewerRef" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="Launch">
import {getCategories, listModelInfo} from "@/api/flowable/bpmn/modelInfo";
import {findNodeAll} from "@/utils/treeHelper";
import BpmnViewer from "@/views/flowable/components/BpmnViewer.vue";
import {startProcessInstanceByKey} from "@/api/process/process.js";
import ProcessWrapper from "@/views/process/components/ProcessWrapper.vue";
const { proxy } = getCurrentInstance();
const activeNames = ref([]);
const activeTabName = ref("formInfo");
const rootCategories = ref([]);
const procInstId = ref('');
const modelKey = ref('');
const currModel = ref(undefined);
// 遮罩层
const loading = ref(true);
const submitLoading = ref(false);
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);
// 弹出层标题
const title = ref("-");
// 是否显示弹出层
const processFormVisible = ref(false);

const categoriesData = ref(undefined);
const modelListData = ref(undefined);

const previewModelKey = ref('');
const bpmnViewerTitle = ref('');
const bpmnViewerVisible = ref(false);

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
})
const handleQuery = async () =>{
  await loadModalData(queryParams.value.keyword||'');
}

const resetQuery = () => {
  proxy.resetForm("queryRef");
  handleQuery();
}

async function handleLaunchCancel(){
  await proxy.$refs.processWrapperRef.resetForm();
}

const submitForm = async () => {
  try {
    submitLoading.value = true;
    const formData = await proxy.$refs.processWrapperRef.getFormData();
    // 组装流程/表单参数
    const params = genSaveData(formData);
    // 发起流程
    // this.submitLoading = true;
    startProcessInstanceByKey(params).then(res =>{
      if(res.success){
        proxy.$modal.msgSuccess(res.msg);
        // 关闭当前窗口
        processFormVisible.value = false;
        setTimeout(()=>{
          // this.$router.replace('/process/launched');
          // this.submitLoading = false;
        }, 1000)
      }else{
        proxy.$modal.msgError(res.msg);
      }
      submitLoading.value = false;
    }).catch(e=>{
      proxy.$modal.msgError("流程发起失败！");
      submitLoading.value = false;
    });
  } catch (e) {
    submitLoading.value = false;
  }
}

const genSaveData = (formData) => {
  const data = {
    modelKey: currModel.value.modelKey,
    currentUserCode: '1',
    businessKey: 'test_businessKey' + (new Date()).getTime(),
    creator: '1',
    appSn: 'flow',
    message: '发起流程',
    formName: formData.title
  };
  data.formData = JSON.stringify({...data, ...formData});
  if(formData.dynamicFields.length > 0){
    const variables = {};
    formData.dynamicFields.forEach(item => {
      variables[item.fieldName] = item.fieldValue;
    })
    data.variables = variables;
  }
  console.log(data);
  return data;
}

// 取消按钮
const cancel = () => {
  processFormVisible.value = false;
}

/** 预览按钮操作 */
const handleBpmnPreview = (item) => {
  bpmnViewerTitle.value = "流程预览-" + item.name;
  bpmnViewerVisible.value = true;
  previewModelKey.value = item.modelKey;
}

async function initData(){
  loading.value = true;
  try {
    const {msg, data: catesData} = await getCategories();
    const {data: modelsData} = await listModelInfo({});

    categoriesData.value = catesData;
    modelListData.value = modelsData;

    await loadModalData('');
    loading.value = false;
  } catch (e) {
    loading.value = false;
  }
}


async function loadModalData(keyword){
  const categories = categoriesData.value;
  loading.value = true;
  const modelList = keyword.trim() !== ''
      ? (modelListData.value.filter(item => item.name.indexOf(keyword)!==-1 || item.modelKey.indexOf(keyword)!==-1))
      : modelListData.value;

  const modelListCateMap = {};
  modelList.forEach(item => {
    if (!modelListCateMap[item.category]) {
      modelListCateMap[item.category] = [];
    }
    modelListCateMap[item.category].push(item);
  })

  const treeList = categories;
  const treeData = proxy.handleTree(treeList, "id", "pid");

  const roots = [];
  treeData.forEach(item => {
    // 获取所有子节点
    const nodes = findNodeAll(treeData, (node) => node.pid === item.id);
    nodes.push(item);
    let tempModelList = [];
    nodes.forEach(itm => {
      const tempModels = modelListCateMap[itm.code]
      if (tempModels && tempModels.length > 0){
        tempModelList = tempModelList.concat(tempModels);
      }
    })
    if (tempModelList.length > 0) {
      item['modelList'] = tempModelList;
      roots.push(item);
    }
  });

  activeNames.value = roots.map(itm => itm.code);
  rootCategories.value = roots;
  loading.value = false;
}

const handleLaunch = (model) => {
  activeTabName.value = 'formInfo';
  currModel.value = model;
  processFormVisible.value = true;
  title.value = `发起【${model.name}】流程`;
}

initData();

</script>

<style lang="scss">
.model-list-wrapper {
  .model-item-card{
    .el-card__body{
      padding: 5px!important;
      position: relative;
      .model-item {
        cursor: pointer;
        width: 100%;
        display: flex;
        align-items: center;
        flex-direction: row;
        .model-icon{
          height: 51px;
          display: flex;
          flex-direction: row;
          align-content: center;
          align-items: center;
        }
        .model-name{
          flex: 1;
          padding-left: 10px;
        }
      }
      .tool-bar{
        display: none;
        position: absolute;
        right: 10px;
        top: 25px;
        cursor: pointer;
      }
    }
    &:hover{
      .tool-bar{
        display: block;
      }
    }
  }

}

.launch-wrapper {
  .el-dialog__body {
    position: relative;
    padding: 0 20px;
    height: calc(100vh - 124px); /* 100vh代表全屏，124px是el-dialog头部以及footer的高度，需要根据实际情况调整 */
    overflow-y: auto; /* 添加滚动条 */
    .right-btn {
      position: absolute;
      right: 10px;
      top: 0px;
    }
  }
}

</style>
